<?php
	include_once('dbcon.php');
	include_once('constants.php');
	include_once('error_log_db.php');

	if (defined("UPDATE_USER_POINTS_DB") == false) {

		define("UPDATE_USER_POINTS_DB", 1);

		// http://amix.dk/blog/post/19588

		function getContentPoints($likes, $dislikes) {
			$total = $likes + $dislikes;

			if ($total == 0)
				return 0;

			$phat = $likes / $total;
			return (($phat + QUANTILE*QUANTILE/(2*$total) - QUANTILE * sqrt(($phat*(1-$phat)+QUANTILE*QUANTILE/(4*$total))/$total))/(1+QUANTILE*QUANTILE/$total))*MAX_POINTS;
		}

		function getCategoryScore($likes, $dislikes, $creation_date) {
			$t_s = strtotime($creation_date) - strtotime(CATEGORY_START_DATE);
			$x = $likes - $dislikes;

			return $x + $t_s/CATEGORY_DATE_RELEVANCE;
		}

		function getUserPoints($user_id) {
			global $mysqli;
			
			$user_query = $mysqli->query("SELECT points FROM users WHERE user_id='".$user_id."'");
			logIfError($mysqli, $user_id, "update_user_points_db", "getUserPoints", "1");
			
			return $user_query->fetch_assoc()['points'];
		}

		function updateUserPoints($user_id) {
			global $mysqli;
			
			$contents = $mysqli->query("SELECT * FROM contents WHERE user_id='".$user_id."'");
			logIfError($mysqli, $user_id, "update_user_points_db", "updateUserPoints", "1");
			
			$total_points = 0;
			
			while ($row = $contents->fetch_assoc()) {

				$total_points += $row['points'];
			}
			
			$mysqli->query("UPDATE users SET points='".$total_points."' WHERE user_id='".$user_id."'");
			logIfError($mysqli, $user_id, "update_user_points_db", "updateUserPoints", "2");
		}

	}	

?>
